package com.wang.mvchain.outer.service.implay;

import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.HTTPUtil;
import com.wang.mvchain.outer.enums.TradeEnum;
import com.wang.mvchain.outer.service.ITradeService;

/**
 * Okex的API工具
 * 
 * @author wangsh
 */
public class OkexTradeServiceImplay extends BaseTradeService implements ITradeService
{
	/* 请求服务的serverUrl */
	private String serverUrl = "https://www.okex.me" ; 
	private String pass = "mvchain" ; 
	
	@Override
	public int findWebsiteId()
	{
		return 13;
	}
	
	/**
	 * 获取最新的时间
	 * @return
	 */
	private String getTime()
	{
		HTTPUtil httpUtil = new HTTPUtil();
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("requestURL", this.serverUrl + "/api/general/v3/time");
		String response = httpUtil.methodGet(paramsMap);
		//ConstatFinalUtil.OUTER_LOG.info("=====getTime====" + response);
		JSONObject responseJSON = (JSONObject) JSON.parse(response);
		return responseJSON.getString("iso");
	}
	
	private String getTime_Old()
	{
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
		// 1、取得本地时间：
		Calendar cal = Calendar.getInstance();
		// 2、取得时间偏移量：
		int zoneOffset = cal.get(java.util.Calendar.ZONE_OFFSET);
		// 3、取得夏令时差：
		int dstOffset = cal.get(java.util.Calendar.DST_OFFSET);
		// 4、从本地时间里扣除这些差量，即可以取得UTC时间：
		cal.add(java.util.Calendar.MILLISECOND, -(zoneOffset + dstOffset));
				
		return sdf.format(cal.getTime());
	}
	
	/**
	 * 往Header中存储信息
	 * @return
	 */
	private Map<String, String> saveHeader()
	{
		Map<String, String> headerMap = new HashMap<String,String>();
		headerMap.put("OK-ACCESS-KEY", authJSON.get("api_key") + "");
		headerMap.put("OK-ACCESS-TIMESTAMP", this.getTime());
		headerMap.put("OK-ACCESS-PASSPHRASE", this.pass);
		return headerMap;
	}

	/**
	 * 获取签名方式
	 * @param json 是一个JSON字符串
	 * @return
	 */
	private String authSign(Map<String, String> headerMap,Map<String, String> requestMap,Object json)
	{
		try
		{
			StringBuffer sb = new StringBuffer();
			
			/* 时间 */
			sb.append(headerMap.get("OK-ACCESS-TIMESTAMP"));
			sb.append(requestMap.get("enc_method"));
			
			if(requestMap.size() > 2)
			{
				sb.append("?");
			}
			for (Iterator iterator = requestMap.entrySet().iterator(); iterator.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				String key = me.getKey() + "" ;
				String value = me.getValue() + ""; 
				if("requestURL".equalsIgnoreCase(key) || key.startsWith("enc_"))
				{
					continue ; 
				}else
				{
					sb.append(key + "=" + value + "&");
				}
			}
			if(sb.toString().endsWith("&"))
			{
				sb.delete(sb.lastIndexOf("&"), sb.length());
			}
			if(json instanceof JSONObject)
			{
				JSONObject jsonObj = (JSONObject) json ; 
				sb.append(jsonObj.toJSONString());
			}
			if(json instanceof JSONArray)
			{
				JSONArray jsonArr = (JSONArray) json ; 
				sb.append(jsonArr.toJSONString());
			}
			/*
			 * 采用HMacSha256加密
			 * */
			byte[] res = HmacUtils.hmacSha256(authJSON.getString("secret_key"), sb.toString());
			String base64 =  Base64.encodeBase64String(res);
			return base64 ; 
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return "" ; 
	}

	/**
	 * 获取用户基本信息
	 * 
	 * @return
	 */
	public JSONObject getUserInfo(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		String methodUrl = "/api/spot/v3/accounts" ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		/* 增加签名参数 */
		requestMap.put("enc_method", "GET" + methodUrl);
		
		/**
		 * 存储Header的一些参数
		 */
		Map<String, String> headerMap = saveHeader();
		
		/* 存储一些交易的参数 */
		
		String sign = authSign(headerMap,requestMap,null);
		headerMap.put("OK-ACCESS-SIGN", sign);
		requestMap.remove("enc_method");
		
		String result = "" ; 
		try
		{
			//result = httpUtil.methodPost(Collections.EMPTY_MAP , paramsMap);
			result = httpUtil.methodGet(headerMap,requestMap);
			JSONArray resArr = (JSONArray) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject();
			
			JSONObject balanceJSON = new JSONObject();
			JSONObject fundJSON = new JSONObject();
			for (Iterator iterator = resArr.iterator(); iterator.hasNext();)
			{
				JSONObject resTempJSON = (JSONObject) iterator.next() ;
				
				/*
				 * {
				        "frozen":"0",
				        "hold":"0",
				        "id":"9150707",
				        "currency":"BTC",
				        "balance":"0.0049925",
				        "available":"0.0049925",
				        "holds":"0"
				    }
				 * */
				String name = resTempJSON.getString("currency").toLowerCase();
				/* 这里面有我们要想的币种 */
				balanceJSON.put(name, resTempJSON.get("balance"));
				fundJSON.put(name, resTempJSON.get("frozen"));
			}
			
			dataJSON.put("balance", balanceJSON);
			dataJSON.put("fund", fundJSON);
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息返回.--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ requestMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 下单交易
	 * 
	 * @return
	 */
	public JSONObject trade(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.trade(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		
		resultJSON = new JSONObject() ;
		//拼装目标数据
		String methodUrl = "/api/spot/v3/orders" ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		/* 增加签名参数 */
		requestMap.put("enc_method", "POST" + methodUrl);
		
		/* 必须是数组 */
		JSONObject ordersTemp = new JSONObject();
		/**
		 * 存储Header的一些参数
		 */
		Map<String, String> headerMap = saveHeader();
		headerMap.put("requestURL", serverUrl + methodUrl);
		headerMap.put("Content-Type", "application/json; charset=UTF-8");
		
		ordersTemp.put("client_oid", "");
		ordersTemp.put("type", "limit");
		/* 存储一些交易的参数 */
		String type = paramsMap.get("type") ; 
		if(TradeEnum.TRADE_TYPE_BUY.getValue() == Integer.valueOf(type))
		{
			/* 买 */
			ordersTemp.put("side", "buy");
		}else if(TradeEnum.TRADE_TYPE_SELL.getValue() == Integer.valueOf(type))
		{
			/* 买 */
			ordersTemp.put("side", "sell");
		}
		/* 交易对 */
		String moneyType = paramsMap.get("moneytype");
		ordersTemp.put("instrument_id", this.convertMoneyType(moneyType));
		/* 交易类型:币币交易 */
		ordersTemp.put("margin_trading", 1);
		/* 订单类型 */
		ordersTemp.put("order_type", "0");
		/* 价格和数量 */
		ordersTemp.put("price", paramsMap.get("price"));
		ordersTemp.put("size", paramsMap.get("amount"));
		
		String sign = authSign(headerMap,requestMap , ordersTemp);
		headerMap.put("OK-ACCESS-SIGN", sign);
		requestMap.remove("enc_method");
		
		requestMap.remove("requestURL");
		
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(headerMap , ordersTemp.toJSONString());
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			
			if("true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("order_id"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error_code"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--下单交易返回--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "下单交易失败."
					+ requestMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 撤销订单
	 * 
	 * @return
	 */
	public JSONObject cancelOrder(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.cancelOrder(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		//拼装目标数据
		resultJSON = new JSONObject();
		String methodUrl = "/api/spot/v3/cancel_orders/" + paramsMap.get("order_id"); 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		/* 增加签名参数 */
		requestMap.put("enc_method", "POST" + methodUrl);
		/* 必须是数组 */
		JSONObject reqJSON = new JSONObject();
		/**
		 * 存储Header的一些参数
		 */
		Map<String, String> headerMap = saveHeader();
		headerMap.put("requestURL", serverUrl + methodUrl);
		headerMap.put("Content-Type", "application/json; charset=UTF-8");
		
		/* 存储一些交易的参数 */
		String moneytype = paramsMap.get("moneytype");
		reqJSON.put("instrument_id", this.convertMoneyType(moneytype));
		
		reqJSON.put("client_oid", "");
		reqJSON.put("order_id", paramsMap.get("order_id"));
		
		String sign = authSign(headerMap,requestMap,reqJSON);
		headerMap.put("OK-ACCESS-SIGN", sign);
		requestMap.remove("enc_method");
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(headerMap , reqJSON.toJSONString());
			JSONObject responseJSON = (JSONObject) JSON.parse(result);
			
			if("true".equalsIgnoreCase(responseJSON.get("result") + ""))
			{
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("order_id"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error_code"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--撤销订单返回.--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "撤销订单失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 获取用户挂单
	 * 
	 * @param args
	 */
	public JSONObject getOrders(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.getOrders(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		resultJSON = new JSONObject() ;
		//拼装目标数据
		String methodUrl = "/api/spot/v3/orders_pending" ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		/* 增加签名参数 */
		requestMap.put("enc_method", "GET" + methodUrl);
		
		/**
		 * 存储Header的一些参数
		 */
		Map<String, String> headerMap = saveHeader();
		
		/* 存储一些交易的参数 */
		String moneyType = paramsMap.get("moneytype") ; 
		requestMap.put("instrument_id", this.convertMoneyType(moneyType));
		
		String sign = authSign(headerMap,requestMap,null);
		headerMap.put("OK-ACCESS-SIGN", sign);
		requestMap.remove("enc_method");
				
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(headerMap , requestMap);
			JSONArray ordersJSON = (JSONArray) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject();
			JSONArray ordersResArr = new JSONArray();
			for (Iterator iterator = ordersJSON.iterator(); iterator
					.hasNext();)
			{
				JSONObject ordersTemp = (JSONObject) iterator.next();
				JSONObject ordersResJSON = this.convertOrders(moneyType, ordersTemp);
				ordersResArr.add(ordersResJSON);
			}
			
			dataJSON.put("ordersList", ordersResArr);
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取用户挂单--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户挂单失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 行情API
	 */
	public JSONObject queryTicker(Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();
		String symbol = paramsMap.get("symbol");
		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					"https://www.okcoin.com/api/ticker.do?symbol=ltc_cny");
		} else
		{
			paramsMap.put("requestURL", "https://www.okcoin.com/api/ticker.do");
		}

		paramsMap.remove("symbol");

		JSONObject resultJSON = new JSONObject();
		try
		{
			String result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONObject) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "行情API失败."
					+ paramsMap, e);
		}
		return resultJSON;
	}

	/**
	 * depth(市场深度)
	 */
	public JSONObject queryDepth(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		String moneyType = paramsMap.get("moneytype");
		moneyType = this.convertMoneyType(moneyType);
		
		String methodUrl = "/api/spot/v3/instruments/"+ moneyType +"/book" ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		/* 增加签名参数 */
		/* 存储一些交易的参数 */
		JSONObject responseJSON = new JSONObject();
		try
		{
			String result = httpUtil.methodGet(requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			
			// 拼装符合条件的json数据
			JSONObject dataJSON = new JSONObject();

			int count = 0;
			// 按照规则排序的容器
			Map<Double, JSONObject> asksMap = new TreeMap<Double, JSONObject>();
			JSONArray asksResArr = new JSONArray();
			JSONArray asksArr = (JSONArray) responseJSON.get("asks");
			for (Iterator iterator = asksArr.iterator(); iterator.hasNext();)
			{
				JSONArray asksTempArr = (JSONArray) iterator.next();
				JSONObject askJSON = new JSONObject();
				askJSON.put("count", "1");
				askJSON.put("vol", asksTempArr.get(1) + "");
				askJSON.put("rate", asksTempArr.get(0) + "");

				asksMap.put(Double.valueOf(askJSON.get("rate") + ""), askJSON);
			}

			for (Iterator iterator = asksMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject asksTemp = (JSONObject) me.getValue();

				asksResArr.add(asksTemp);
				count++;
			}

			dataJSON.put("asks", asksResArr);

			// 按照规则排序的容器
			count = 0;
			Map<Double, JSONObject> bidsMap = new TreeMap<Double, JSONObject>(
					new Comparator<Double>()
					{
						@Override
						public int compare(Double o1, Double o2)
						{
							return o2.compareTo(o1);
						}
					});
			JSONArray bidsResArr = new JSONArray();
			JSONArray bidsArr = (JSONArray) responseJSON.get("bids");
			for (Iterator iterator = bidsArr.iterator(); iterator.hasNext();)
			{
				JSONArray bidsTempArr = (JSONArray) iterator.next();
				JSONObject bidsJSON = new JSONObject();
				bidsJSON.put("count", "1");
				bidsJSON.put("vol", bidsTempArr.get(1) + "");
				bidsJSON.put("rate", bidsTempArr.get(0) + "");

				bidsMap.put(Double.valueOf(bidsJSON.get("rate") + ""), bidsJSON);
			}

			for (Iterator iterator = bidsMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject bidsTemp = (JSONObject) me.getValue();

				bidsResArr.add(bidsTemp);
				count++;
			}
			dataJSON.put("bids", bidsResArr);

			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			resultJSON.put("data", dataJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "depth(市场深度)失败."
					+ paramsMap, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * trades的格式,历史交易记录
	 */
	public JSONArray queryHistoryTrades(String symbol,
			Map<String, String> paramsMap)
	{

		HTTPUtil httpUtil = new HTTPUtil();

		if ("ltc_cny".equalsIgnoreCase(symbol))
		{
			paramsMap.put("requestURL",
					" https://www.okcoin.com/api/trades.do?symbol=ltc_cny");
		} else
		{
			paramsMap.put("requestURL",
					" https://www.okcoin.com/api/trades.do?");
		}
		JSONArray resultJSON = new JSONArray();
		try
		{
			String result = httpUtil.methodGet(paramsMap);
			resultJSON = (JSONArray) JSON.parse(result);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "历史交易记录失败."
					+ paramsMap, e);
		}
		return resultJSON;
	}

	@Override
	public String toString()
	{
		return "OkexTradeServiceImplay [findid()=" + findWebsiteId() + "]";
	}

	@Override
	public JSONObject getOrdersSingle(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = super.getOrdersSingle(paramsMap);
		if(resultJSON != null)
		{
			return resultJSON ; 
		}
		
		resultJSON = new JSONObject();
		//拼装目标数据
		String methodUrl = "/api/spot/v3/orders/" + paramsMap.get("order_id") ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		/* 增加签名参数 */
		requestMap.put("enc_method", "GET" + methodUrl);
		
		/**
		 * 存储Header的一些参数
		 */
		Map<String, String> headerMap = saveHeader();
		
		/* 存储一些交易的参数 */
		String moneyType = paramsMap.get("moneytype") ; 
		requestMap.put("instrument_id", this.convertMoneyType(moneyType));
		requestMap.put("order_id", paramsMap.get("order_id"));
		requestMap.put("client_oid", "");
		
		String sign = authSign(headerMap,requestMap,null);
		headerMap.put("OK-ACCESS-SIGN", sign);
		requestMap.remove("enc_method");
		
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(headerMap , requestMap);
			JSONObject ordersTemp = (JSONObject) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject() ; 
			if((ordersTemp.get("order_id") + "").equalsIgnoreCase(paramsMap.get("order_id") + ""))
			{
				JSONObject ordersResJSON = this.convertOrders(moneyType, ordersTemp);
				dataJSON.put("orders", ordersResJSON);
			}
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取订单详情--原始信息:" + result
				+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败."
					+ paramsMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	@Override
	public String findWebSiteName()
	{
		return "OkEx";
	}

	@Override
	public JSONObject convertOrders(String moneytype, JSONObject ordersTemp)
	{
		try
		{
			JSONObject ordersResJSON = new JSONObject();
			ordersResJSON.put("order_id", ordersTemp.get("order_id") + "");
			ordersResJSON.put("price", ordersTemp.get("price") + "");
			ordersResJSON.put("amount", ordersTemp.get("size") + "");
			ordersResJSON.put("deal_amount", ordersTemp.get("filled_size") + "");
			/* avg_price:实际成交的价格 */
			double avgTotalPrice = Double.valueOf(ordersTemp.get("filled_notional") + "");
			double deal_amount = Double.valueOf(ordersResJSON.get("deal_amount") + "");
			double avg_price = 0 ;
			if(deal_amount > 0)
			{
				avg_price = avgTotalPrice / deal_amount ; 
			}
			/* 实际价格往高了算 */
			avg_price = this.doubleOperUtil.round(avg_price, 3, RoundingMode.UP.ordinal()) ; 
			
			ordersResJSON.put("avg_price", avg_price);
			/* 创建订单的时间 */
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
			String createTime = ordersTemp.get("created_at") + "";
			Date createDate = sdf.parse(createTime);
			ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
			
			String symbol = ordersTemp.get("instrument_id") + "";
			ordersResJSON.put("symbol", this.parseMoneyType(symbol));
			/* 交易类型 */
			String type = ordersTemp.get("side") + "";
			if("buy".equalsIgnoreCase(type))
			{
				type = TradeEnum.TRADE_TYPE_BUY.getValue() + "" ; 
			}else if("sell".equalsIgnoreCase(type))
			{
				type = TradeEnum.TRADE_TYPE_SELL.getValue() + "" ; 
			}
			ordersResJSON.put("type", type);
			
			/* 默认未成交 */
			String status = TradeEnum.TRADE_STATUS_DEAL_NO.getValue() + ""; 
			/*
			 * -1:已撤销  0:未成交  1:部分成交  2:完全成交 3 撤单处理中
			 * */
			if("cancelled".equalsIgnoreCase(ordersTemp.get("status") + ""))
			{
				status = TradeEnum.TRADE_STATUS_CANCEL.getValue() + ""; 
			}else if("open".equalsIgnoreCase(ordersTemp.get("status") + ""))
			{
				status = TradeEnum.TRADE_STATUS_DEAL_NO.getValue() + ""; 
			}else if("part_filled".equalsIgnoreCase(ordersTemp.get("status") + ""))
			{
				status = TradeEnum.TRADE_STATUS_DEAL_PART.getValue() + ""; 
			}else if("filled".equalsIgnoreCase(ordersTemp.get("status") + ""))
			{
				status = TradeEnum.TRADE_STATUS_DEALED.getValue() + ""; 
			}
			ordersResJSON.put("status", status);
			return ordersResJSON;
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOG.error("转换订单报错了",e);
		}
		return new JSONObject();
	}

	@Override
	public String convertMoneyType(String moneytypeSelf)
	{
		return moneytypeSelf.replace("_", "-").toUpperCase();
	}

	@Override
	public String parseMoneyType(String moneytypeTrade)
	{
		return moneytypeTrade.replace("-", "_").toLowerCase();
	}
	
	@Override
	public JSONObject findAllTransPair(Map<String, String> paramsMap)
	{
		JSONObject resultJSON =  super.findAllTransPair(paramsMap);
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		String methodUrl = "/api/spot/v3/instruments" ; 
		
		HTTPUtil httpUtil = new HTTPUtil();
		/* 公共代码 */
		Map<String, String> requestMap = new HashMap<String, String>();
		requestMap.put("requestURL", serverUrl + methodUrl);
		/* 增加签名参数 */
		requestMap.put("enc_method", "GET" + methodUrl);
		
		/* 存储一些交易的参数 */
		requestMap.remove("enc_method");
		
		String result = "" ; 
		try
		{
			//result = httpUtil.methodPost(Collections.EMPTY_MAP , paramsMap);
			result = httpUtil.methodGet(Collections.EMPTY_MAP,requestMap);
			JSONArray resArr = (JSONArray) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject();
			for (Iterator iterator = resArr.iterator(); iterator.hasNext();)
			{
				JSONObject resTempJSON = (JSONObject) iterator.next() ;
				/*
				 * {
				        //交易货币币种,小写;
				        "base_currency":"BTC",
				        //币对名称,小写;
				        "instrument_id":"BTC-USDT",
				        //最小交易数量
				        "min_size":"0.001",
				        //计价货币币种,小写;
				        "quote_currency":"USDT",
				        //交易货币数量精度
				        "size_increment":"0.00000001",
				        //交易价格精度
				        "tick_size":"0.1"
				    }
				 * */
				JSONObject pairJSON = new JSONObject();
				String moneyType = resTempJSON.getString("instrument_id");
				moneyType = this.parseMoneyType(moneyType);
				
				if(!moneyType.endsWith("usdt"))
				{
					continue ; 
				}
				
				pairJSON.put("name", moneyType);
				pairJSON.put("min_size", resTempJSON.get("min_size"));
				pairJSON.put("base_currency", resTempJSON.getString("base_currency").toLowerCase());
				pairJSON.put("quote_currency", resTempJSON.getString("quote_currency").toLowerCase());
				pairJSON.put("size_increment", resTempJSON.get("size_increment"));
				pairJSON.put("tick_size", resTempJSON.get("tick_size"));
				/* 存储到结果中 */
				dataJSON.put(pairJSON.get("name") + "", pairJSON);
			}
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息返回.--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败."
					+ requestMap + ";原始信息:" + result, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}
}
